package com.holyshit.exam.net;

import android.support.annotation.NonNull;

import com.google.gson.Gson;
import com.holyshit.exam.utils.LogUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by thinkpad on 2016/6/2.
 */
public class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {


    private final Gson gson;
    private final Type type;

    GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    @Override
    public T convert(@NonNull ResponseBody value) throws IOException {
        Reader reader = value.charStream();
        BufferedReader in = new BufferedReader(reader);
        StringBuilder buffer = new StringBuilder();
        String line = "";
        while ((line = in.readLine()) != null) {
            buffer.append(line);
        }
        LogUtil.e("解密前响应报文: ", buffer.toString());
        LogUtil.e("解密后响应报文：", buffer.toString());
        try {
            return gson.fromJson(buffer.toString(), type);
        } finally {
            try {
                reader.close();
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
